import React from 'react';
import './cptColorPercent.less';

export class ColorPercent extends React.Component {
    static defaultProps = {
        prefixCls: 'cpt-color-percent-wrapper',
        needStep: false,        //是否需要阶梯状渲染
        stepRange: {min: 5, max: 25},        //数量处于区间[5,25]中，且needStep为true，则进行阶梯状渲染,
        borderRadiusNum: 0
    };

    constructor(props) {
        super(props);
        this.state = {
            sum: 0
        };
    }

    componentDidMount() {
        this.computeRate(this.props);
        this.drawProgress(this.props);
    }

    componentWillReceiveProps(next, p) {
        this.computeRate(next);
        this.drawProgress(next);
    }


    computeRate = (props) => {
        const {options} = props;
        let count = 0;
        options.forEach((item) => {
            const num = parseFloat(item.num);
            if (num && num >= 0) {
                count += num;
            }
        });
        this.setState({sum: count});
        options.forEach((item) => {
            item.rate = parseFloat(item.num) / count;
        })
    };
    drawProgress = (props) => {
        const {options, needStep, borderRadiusNum, stepRange} = props;
        const {onTouch} = props;

        this.clearDraw();//清空画布
        let parent = document.querySelector('#cpt_color_percent_wrapper');
        options.forEach((item, index) => {

            if (item.rate >= 0) {
                if (!item.colorEnd) {
                    item.colorEnd = item.colorBegin;
                }
                let elem = document.createElement('div');
                elem.style.width = item.rate * 100 + '%';//渲染宽度
                // if(item.rate===0){
                // elem.style.borderLeft='1px solid'+item.colorBegin;
                // }
                elem.style.height = parseFloat(parent.style.width) + 'px';
                elem.className = 'cpt-color-percent-item';
                elem.style.borderRadius = parseInt(borderRadiusNum, 10) + 'px';
                elem.addEventListener('touchstart', () => {
                    onTouch(item, this.state.sum);
                    elem.style.transform = 'scaleY(1.1)';
                }, false);
                elem.addEventListener('touchend', () => {
                    elem.style.transform = 'scaleY(1)'
                }, false);

                if (index !== 0) {
                    elem.style.marginLeft = '8px';
                }
                if (stepRange.max < stepRange.min) {
                    const tmp = stepRange.max;
                    stepRange.max = stepRange.min;
                    stepRange.min = tmp;
                }
                const colorArr = new gradientColor(item.colorBegin, item.colorEnd, item.num);

                if ((needStep) && (item.num >= stepRange.min && item.num <= stepRange.max)) {       //是否需要阶梯渐变,阶梯渐变范围
                    if (colorArr.length === 1) {
                        if (stepRange.min <= 1) {
                            elem.style.background = colorArr.pop();
                        } else {
                            elem.style.filter = "progid:DXImageTransform.Microsoft.Gradient(startColorStr=" + item.colorBegin + ",endColorStr=" + item.colorEnd + ",gradientType='0')";
                            elem.style.background = '-moz-linear-gradient(to right,' + item.colorBegin + ',' + item.colorEnd + ')';
                            elem.style.background = '-o-linear-gradient(to right,' + item.colorBegin + ',' + item.colorEnd + ')';
                            elem.style.background = '-webkit-linear-gradient(to right,' + item.colorBegin + ',' + item.colorEnd + ')';
                            elem.style.background = 'linear-gradient(to right,' + item.colorBegin + ',' + item.colorEnd + ')';
                        }
                    } else {
                        colorArr.forEach((c) => {
                            let colorStepItem = document.createElement('div');
                            colorStepItem.style.width = 1 / item.num * 100 + '%';
                            colorStepItem.style.height = parseFloat(parent.style.width) + 'px';
                            colorStepItem.style.background = c;
                            elem.appendChild(colorStepItem);
                        })
                    }
                } else {
                    elem.style.filter = "progid:DXImageTransform.Microsoft.Gradient(startColorStr=" + item.colorBegin + ",endColorStr=" + item.colorEnd + ",gradientType='0')";
                    elem.style.background = '-moz-linear-gradient(to right,' + item.colorBegin + ',' + item.colorEnd + ')';
                    elem.style.background = '-o-linear-gradient(to right,' + item.colorBegin + ',' + item.colorEnd + ')';
                    elem.style.background = '-webkit-linear-gradient(to right,' + item.colorBegin + ',' + item.colorEnd + ')';
                    elem.style.background = 'linear-gradient(to right,' + item.colorBegin + ',' + item.colorEnd + ')';
                }
                parent.appendChild(elem);
            }
        })
    };
    clearDraw = () => {
        let parent = document.querySelector('#cpt_color_percent_wrapper');
        parent.innerHTML = "";
    };

    render() {
        const {prefixCls, className} = this.props;
        return (
            <div id="cpt_color_percent_wrapper" className={`${prefixCls} ${className}`}/>
        )
    }
}

//阶梯渐变
class gradientColor {
    constructor(startColor, endColor, step) {
        if (!endColor) {
            endColor = startColor;
        }
        let startRGB = this.colorRgb(startColor);//转换为rgb数组模式
        let startR = startRGB[0];
        let startG = startRGB[1];
        let startB = startRGB[2];

        let endRGB = this.colorRgb(endColor);
        let endR = endRGB[0];
        let endG = endRGB[1];
        let endB = endRGB[2];

        let sR = (endR - startR) / step;//总差值
        let sG = (endG - startG) / step;
        let sB = (endB - startB) / step;

        let colorArr = [];
        for (let i = 0; i < step; i++) {
            //计算每一步的hex值
            let hex = this.colorHex('rgb(' + parseInt((sR * i + startR), 10) + ',' + parseInt((sG * i + startG), 10) + ',' + parseInt((sB * i + startB), 10) + ')');
            colorArr.push(hex);
        }
        return colorArr;
    }

    // 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
    colorRgb(hexColor) {
        let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        let sColor = hexColor.toLowerCase();
        if (sColor && reg.test(sColor)) {
            if (sColor.length === 4) {
                let sColorNew = "#";
                for (let i = 1; i < 4; i += 1) {
                    sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
                }
                sColor = sColorNew;
            }
            //处理六位的颜色值
            let sColorChange = [];
            for (let i = 1; i < 7; i += 2) {
                sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2), 16));
            }
            return sColorChange;
        } else {
            return sColor;
        }
    }

    colorHex(rgbColor) {
        let _this = rgbColor;
        let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        if (/^(rgb|RGB)/.test(_this)) {
            let aColor = _this.replace(/(?:(|)|rgb|RGB)*/g, "").split(",");
            let strHex = "#";
            for (let i = 0; i < aColor.length; i++) {
                let hex = Number(aColor[i]).toString(16);
                hex = hex < 10 ? 0 + '' + hex : hex;// 保证每个rgb的值为2位
                if (hex === "0") {
                    hex += hex;
                }
                strHex += hex;
            }
            if (strHex.length !== 7) {
                strHex = _this;
            }
            return strHex;
        } else if (reg.test(_this)) {
            let aNum = _this.replace(/#/, "").split("");
            if (aNum.length === 6) {
                return _this;
            } else if (aNum.length === 3) {
                let numHex = "#";
                for (let i = 0; i < aNum.length; i += 1) {
                    numHex += (aNum[i] + aNum[i]);
                }
                return numHex;
            }
        } else {
            return _this;
        }
    }

}
